<template>
  <div class="user-share-card">
    <div class="jm-nav-bar flex-align-center" v-if="$UA.isJM">
      <van-icon @click="$appService.exit()" name="arrow-left" size="1.6rem" />
      <p class="nav-title">个人海报</p>
      <div class="edit-btn" @click="toEdit" v-if="userInfo.uuid && appUser.uuid == userInfo.uuid">
        编辑资料
      </div>
    </div>
    <div class="box-shadow" v-show="userInfo.uuid">
      <div class="image-wrapper" ref="imageWrapper">
        <div class="userinfo-layout">
          <img
            class="cover loadImgs"
            crossorigin="anonymous"
            v-if="userInfo.cover"
            :src="`${userInfo.cover}?x-oss-process=image/resize,m_fill,w_335,h_420`"
          />
          <img
            class="cover-shade loadImgs"
            crossorigin="anonymous"
            v-if="userInfo.avatar"
            src="@/assets/images/share/user-card-bg.png"
          />
          <div class="baseinfo">
            <div class="avatar">
              <img
                crossorigin="anonymous"
                v-if="userInfo.avatar"
                class="loadImgs"
                :src="`${userInfo.avatar}?x-oss-process=image/resize,m_fill,w_152,h_152`"
              />
            </div>
            <p class="nickname">{{ userInfo.nickname }}</p>
            <div class="auth flex-align-center" v-if="userInfo.identified">
              <img
                src="@/assets/images/activity/authentication-person.png"
                crossorigin="anonymous"
                class="icon-auth loadImgs"
                v-if="userInfo.identified == 1"
              />
              <img
                src="@/assets/images/activity/authentication-organization.png"
                crossorigin="anonymous"
                class="icon-auth loadImgs"
                v-if="userInfo.identified == 2"
              />
              <!-- <span v-for="(text, index) in userInfo.identifiedTitle" :key="index">{{ text }}</span> -->
              <!-- 图片和文字没法对齐，先只搞一行吧，用背景图可以对齐但是图标很模糊 -->
              <div class="auth-text">认证：{{ userInfo.identifiedTitle }}</div>
            </div>
            <div class="auth flex-align-center" v-else>
              {{ userInfo.city }}
              {{ userInfo.profession }}
            </div>
            <div class="desc ability" v-if="userInfo.identified == 2 && userInfo.ability">
              <!-- 一大段文字会文字超出既定的区域 -->
              <!-- {{ userInfo.ability }} -->
              <span v-for="(text, index) in userInfo.ability" :key="index">{{ text }}</span>
            </div>
            <div class="desc" v-else>{{ userInfo.intro }}</div>
          </div>
        </div>
        <div class="qrcode-layout flex-align" v-if="userInfo.avatar">
          <canvas id="qrcode"></canvas>
          <div class="share-text">
            <p>长按识别二维码</p>
            <p>查看作品、沟通合作</p>
          </div>
          <div class="icon-jimu">
            <img class="loadImgs" crossorigin="anonymous" src="@/assets/images/badge/logo.png" />
          </div>
        </div>
      </div>
      <img class="share-img" :src="shareInfo.image" v-if="shareInfo.image" />
    </div>
    <van-loading v-if="!userInfo.uuid || !shareInfo.image"></van-loading>
    <share-bottom-btn v-if="shareInfo.image" :shareInfo.sync="shareInfo"></share-bottom-btn>
  </div>
</template>
<script>
  import QRCode from 'qrcode';
  import ShareBottomBtn from '../../components/ShareBottomBtn.vue';
  import html2canvas from 'html2canvas';
  import qs from 'qs';
  import { loading, icon, Toast } from 'vant';

  export default {
    components: {
      ShareBottomBtn,
      'van-icon': icon,
      'van-loading': loading,
    },
    data() {
      return {
        shareInfo: { image: '' },
        userInfo: { avatar: '', cover: '', shareInfo: { url: '' } },
        query: qs.parse(window.location.href.split('?')[1]),
        appUser: {},
        cardBgImg:
          'https://ketang-pub.movtile.com/res/jimu-share-card-bg-1222.png?x-oss-process=image/resize,m_fill,w_335,h_420',
        // 二维码配置
        opts: {
          errorCorrectionLevel: 'L', //容错级别
          type: 'image/png', //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 0, //二维码留白边距
          width: 50, //宽
          height: 50, //高
          color: {
            dark: '#000', //前景色
            light: '#fff', //背景色
          },
        },
      };
    },
    mounted() {
      this.$appService.setNav({
        title: '个人海报',
        fullscreen: true,
      });
      this.getUserInfo();
      this.$EventBus.$on('jm:hybridActive', () => {
        this.getUserInfo();
      });
      this.$appService
        .userInfo()
        .then((res) => {
          this.appUser = res;
        })
        .catch((err) => {});
    },
    methods: {
      getUserInfo() {
        this.userInfo = { avatar: '', cover: '', shareInfo: { url: '' } };
        this.shareInfo.image = '';
        if (!this.query.uuid) {
          this.$appService.toast({ msg: '链接缺少ID' });
          return;
        }
        this.$service
          .UserInfoDetail({
            uuid: this.query.uuid,
          })
          .then((res) => {
            this.userInfo = res;
            // html2canvas 的时候不能用省略号，判断长度自己加一个
            if (this.userInfo.ability && this.userInfo.ability.length > 105) {
              this.userInfo.ability = res.ability.substring(0, 105) + '...';
            }
            if (this.userInfo.identifiedTitle && this.userInfo.identifiedTitle.length > 16) {
              this.userInfo.identifiedTitle = res.identifiedTitle.substring(0, 14) + '...';
            }
            this.$nextTick(() => {
              this.loadingImage();
            });
          })
          .catch((err) => {
            Toast(err.message);
            console.log(err);
          });
      },
      loadingImage() {
        // loading图片
        const newLoadImgArr = document.getElementsByClassName('loadImgs');
        let imgPromiseAll = [];
        for (let index = 0; index < newLoadImgArr.length; index++) {
          imgPromiseAll[index] = new Promise((resolve, reject) => {
            newLoadImgArr[index].onload = function (e) {
              resolve(index);
            };
            newLoadImgArr[index].onerror = (e) => {
              resolve(index);
            };
          });
        }
        // 制作二维码
        imgPromiseAll.concat(
          new Promise((resolve, reject) => {
            QRCode.toCanvas(
              document.getElementById('qrcode'),
              this.userInfo.shareInfo.url,
              this.opts,
              (error) => {
                if (error) {
                  console.log(error);
                  reject();
                }
                resolve();
              },
            );
          }),
        );

        Promise.all(imgPromiseAll)
          .then((img) => {
            console.log('load all');
            //全部加载完成
            this.makeImage();
          })
          .catch((err) => {
            Toast(`出错了`);
          });
      },
      makeImage() {
        // 生成图片
        html2canvas(this.$refs.imageWrapper, {
          allowTaint: true,
          useCORS: true,
          scale: 4,
          // dpi: 300, // 处理模糊
        }).then((canvas) => {
          this.shareInfo.image = canvas.toDataURL('image/png');
        });
      },
      toEdit() {
        this.$appService.openLink({
          link: 'mtjimu://account',
        });
      },
    },
  };
</script>
<style lang="less" scoped>
  .user-share-card {
    color: #111111;
    padding: 4.8rem 2rem 24rem;
    font-size: 1.4rem;
    font-family: 'PingFang SC';
    .jm-nav-bar {
      text-align: center;
      height: 4rem;
      justify-content: space-between;
      margin-bottom: 1.2rem;
      .nav-title {
        font-size: 1.8rem;
        font-weight: 800;
        color: #111111;
        width: 100%;
        position: absolute;
        left: 0;
        z-index: -1;
      }
      .edit-btn {
        font-size: 1.4rem;
        font-weight: 400;
        color: #111111;
        background-image: url(https://ketang-pub.movtile.com/res/jimu-icon-pen-1223.png);
        background-position: 0 center;
        background-repeat: no-repeat;
        background-size: 1.6rem;
        padding-left: 2rem;
      }
    }
    .box-shadow {
      width: 100%;
      background: #ffffff;
      box-shadow: 0rem 0rem 3rem 0rem rgba(0, 0, 0, 0.1);
      border-radius: 0.5rem;
      overflow: hidden;
      .image-wrapper {
        width: 33.5rem;
        height: 50rem;
        margin: auto;
        position: fixed;
        left: -1000rem;
        .userinfo-layout {
          height: 42rem;
          position: relative;
          text-align: center;
          overflow: hidden;
          .cover,
          .cover-shade,
          .baseinfo {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            height: 100%;
          }
          .cover-shade {
            // opacity: 0.8;
          }
          .baseinfo {
            color: #ffffff;
            font-size: 1.4rem;
            position: relative;
            .avatar {
              width: 7.6rem;
              height: 7.6rem;
              // border-radius: 50%;
              background-color: #ffffff;
              // border: 0.3rem solid #ffffff;
              display: block;
              margin: 7rem auto 2.4rem;
              overflow: hidden;
              display: flex;
              align-items: center;
              justify-content: center;
              img {
                width: 7rem;
                height: 7rem;
                border-radius: 50%;
              }
            }
            .nickname {
              font-size: 1.8rem;
              font-weight: 800;
              margin: 2.4rem auto;
              // background-color: #888;
              line-height: 1;
            }
            .auth {
              padding: 0 2rem;
              margin: 2.4rem auto 5rem;
              // flex-wrap: wrap;
              // align-items: baseline;
            }
            .icon-auth {
              width: 1.4rem;
              height: 1.4rem;
              margin-right: 0.7rem;
              flex: none;
            }
            .auth-text {
              margin-top: -0.2rem;
            }
            .desc {
              padding: 0 2rem;
              overflow: hidden;
              max-height: 10.1rem;
              &.ability {
                text-align: left;
              }
            }
          }
        }
      }
      .qrcode-layout {
        height: 8rem;
        background: #ffffff;
        border-radius: 0.5rem;
        padding: 1.5rem;
        canvas {
          width: 5rem;
          height: 5rem;
          margin-right: 1.5rem;
          flex: none;
        }
        position: relative;
        justify-content: space-between;
        .share-text {
          // margin-top: -1.4rem;
          letter-spacing: 0.1rem;
          // background-color: #888;
          width: 100%;
          p {
            line-height: 2.4rem;
            color: #333333;
            font-family: PingFang SC;
            &:first-child {
              font-weight: 800;
            }
          }
        }
      }
    }

    .icon-jimu {
      width: 70px;
      height: 23px;
      // background: url(../../assets/images/badge/logo.png) no-repeat;
      // background-size: 70px 23px;
      flex: none;
      img {
        width: 100%;
      }
    }
    .share-img {
      width: 100%;
    }
  }
  .van-loading {
    margin: 10rem auto;
    text-align: center;
  }
</style>
